import { defineStore } from 'pinia';
import defaultSettings from '@/settings';
import { parse, stringify } from 'zipson';
import { has } from 'lodash-es';

// setup
export const useSettingsStore = defineStore(
  'settings',
  () => {
    let settings = reactive({
      ...defaultSettings,
      title: ''
    });

    // 设置网页标题
    function setTitle(val) {
      settings.title = val;
      document.title = defaultSettings.title;
      if (settings.dynamicTitle) {
        document.title = val + ' - ' + defaultSettings.title;
      }
    }

    function handleSetting({ key, value }) {
      if (has(settings, key)) {
        settings[key] = value;
      }
    }
    return {
      settings,
      handleSetting,
      setTitle
    };
  },
  {
    persist: {
      paths: ['settings.theme', 'settings.language'],
      serializer: {
        deserialize: parse,
        serialize: stringify
      }
    }
  }
);
